/**
 * @description App Component, App Layout
 */

import React, { Component } from 'react'
import { renderRoutes, matchRoutes } from 'react-router-config'
import { routes } from '../router'
import { Layout } from 'antd'
import PropTypes from 'prop-types'
import Header from './layout/Header'
import LeftMenu from './layout/LeftMenu'
import Footer from './layout/Footer'
import QueueAnim from 'rc-queue-anim'

const { Content } = Layout
// Save pre history location
// To be back when not found
let prePathname = ''

// Handle router when component refresh
const handleRouter = (preProps, props) => {
  // TODO: will store login flag
  const hasLogin = sessionStorage.getItem('ri-login')

  if (hasLogin) {
    const branch = matchRoutes(routes, props.location.pathname)
    if (branch.length > 1) {
      // Realtime refresh prePathname
      prePathname = props.location.pathname
    } else {
      props.history.replace(prePathname)
      preProps &&
        preProps.location.pathname !== '/not-found' &&
        props.history.push('/not-found')
    }
  } else {
    props.history.push('/login')
  }
}

export default class App extends Component {
  static propTypes = {
    location: PropTypes.object,
    route: PropTypes.object,
    history: PropTypes.object
  }
  UNSAFE_componentWillMount() {
    handleRouter(null, this.props)
  }
  UNSAFE_componentWillUpdate(props) {
    handleRouter(this.props, props)
  }
  render() {
    return (
      <QueueAnim className="h-100">
        <Layout className="h-100">
          <Header history={this.props.history} />
          <Layout className="flex-row main-container">
            <LeftMenu location={this.props.location} />
            <Content className="h-100">
              {renderRoutes(this.props.route.routes)}
            </Content>
          </Layout>
          <Footer />
        </Layout>
      </QueueAnim>
    )
  }
}
